package com.ifcar.app.activity.microhot;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.ifcar.app.activity.HomePage;
import com.ifcar.app.adapter.MicroHotAdapter;
import com.ifcar.app.fragment.NRPullLoadingListFrament;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.util.FileUtils;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.activity.R;
import com.netease.util.Pair;

public class MicroHotBlogFragment extends NRPullLoadingListFrament{
	
	private Context mContext;
	private ListView mMicroHotListView;
	private MicroHotAdapter mMicroHotAdapter;
	
	private List<Pair<Map<String, Object>, List<Map<String, Object>>>> mWbListData = new ArrayList<Pair<Map<String, Object>, List<Map<String, Object>>>>();
	
	private int startLoaddingNumber = 0;
	private int perLoaddingNumber = 10;
	
	private boolean mIsGetMore = false;
	
	private View v ;
	public MicroHotBlogFragment(){
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mContext = getActivity();
		setRefreshTag(HomePage.MICROHOT);
	}
	
	@Override
	public View onCreateView(final LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		v = inflater.inflate(R.layout.microhot_layout, null);
		return v;
	}
	
	@Override
	public void onViewCreatedNR(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreatedNR(view, savedInstanceState);
		mMicroHotListView = getListView();
		mMicroHotListView.setDividerHeight(0);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		setLoadingNum(perLoaddingNumber);
//		startLoading();
		selectInTab();
	}
	

    @Override
	public ListAdapter getAdapter() {
		return mMicroHotAdapter;
	}
	
	@Override
	public void onTabSelected(boolean first) {
		super.onTabSelected(first);
       
		if (first) {
			startLoading();
		}
	}
	
	@Override
    protected void onLoading() {
        super.onLoading();
        
        List<Pair<Map<String,Object>, List<Map<String,Object>>>> list = FileUtils.readMicroHotData(HomePage.MICROHOT);
		
        Message msg = getHandler().obtainMessage(MSG_LOADING);
        msg.obj = list;
        getHandler().dispatchMessage(msg);
        
    }
	
	@Override
    protected void onHandleLoading(Object result) {
        super.onHandleLoading(result);
        List<Pair<Map<String,Object>, List<Map<String,Object>>>> list = (List<Pair<Map<String,Object>, List<Map<String,Object>>>>) result;
        
        if(null != list && list.size() > 0){
            callLoadingListViewAddMoreView();
        	setData(list);
        } else {
            callLoadingListViewRemoveMoreView();
        }
        
        if (list != null && list.size() > 0) {
            if (isNeedRefresh()) {
                getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refresh();
                    }
                }, 200);
            }
        } else {
            refresh();
        }
    }
	
	@Override
    protected void onRefreshing() {
        super.onRefreshing();
        callLoadingListViewStartLoading(null == mWbListData || mWbListData.size() == 0);
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 取网络
            	List<Pair<Map<String,Object>,List<Map<String,Object>>>> list = getDataFromNet();
            	
                Message msg = getHandler().obtainMessage(MSG_REFRESHING);
                msg.obj = list;
                getHandler().sendMessage(msg);
            }
        }).start();
    }
	
	/**
	 * 获取网络数据
	 * @return
	 */
	private List<Pair<Map<String,Object>,List<Map<String,Object>>>> getDataFromNet(){
				
		String url = String.format(GetColumnsInfo.MicroHost_Url, startLoaddingNumber, perLoaddingNumber);
		
		List<Pair<Map<String,Object>,List<Map<String,Object>>>> list = GetColumnsInfo.getMicroHotData(mContext, url);
		
		if(null != list && startLoaddingNumber == 0){
			FileUtils.writeMicroHotToLocal(list, HomePage.MICROHOT, mContext);
		}
		
		return list;
	}
	
	@Override
	protected void onHandleRefreshing(Object result) {
		super.onHandleRefreshing(result);
		List<Pair<Map<String,Object>, List<Map<String,Object>>>> list = (List<Pair<Map<String,Object>, List<Map<String,Object>>>>) result;
		
        if (list != null && list.size() > 0) {
            callLoadingListViewAddMoreView();
        } else if (mMicroHotAdapter == null || mMicroHotAdapter.getCount() == 0) {
            callLoadingListViewRemoveMoreView();
        }
		setData(list);
	}
	
	@Override
	protected void onLoadingMore() {
		super.onLoadingMore();
		mIsGetMore = true;
		changetStartNum(true);
		getMoreButton().setEnabled(false);
		new Thread(){
			public void run() {
				List<Pair<Map<String,Object>,List<Map<String,Object>>>> list = getDataFromNet();
				
				Message msg = getHandler().obtainMessage(MSG_LOADING_MORE);
				msg.obj = list;
				getHandler().sendMessage(msg);
				
			};
		}.start();
	}
	
	@Override
    protected void onHandleLoadingMore(Object result) {
        super.onHandleLoadingMore(result);
        
        List<Pair<Map<String,Object>,List<Map<String,Object>>>> list = (List<Pair<Map<String,Object>,List<Map<String,Object>>>>) result;
        setData(list);
        
        mIsGetMore = false;
    }
		
	private void setData(List<Pair<Map<String, Object>, List<Map<String, Object>>>> list) {
		// TODO Auto-generated method stub

        if(null != list && list.size() > 0){
			setMicroHotData(list);
			callLoadingListViewCompleteLoading(true, true);
		}else {
			if(mIsGetMore){
				changetStartNum(false);
			}
			
			if(null == list){
			    Toast.makeText(getActivity(), R.string.msg_loading_failed, Toast.LENGTH_SHORT).show();
			    callLoadingListViewCompleteLoading(false, true);
			}else if(list.size() == 0){
			    Toast.makeText(getActivity(), R.string.microhot_is_notmore, Toast.LENGTH_SHORT).show();
			    callLoadingListViewCompleteLoading(true, false);
			}
		
		}
	}
	
	/**
	 * 修改起始位置
	 * @param isadd
	 */
	private void changetStartNum(boolean isadd){
		if(isadd){
			startLoaddingNumber += perLoaddingNumber;
		} else {
			startLoaddingNumber -= perLoaddingNumber;
		}
	}

	/**
	 * 下拉刷新
	 */
	@Override
	public void refresh() {
		super.refresh();
		startLoaddingNumber = 0;
	}
	
	protected void setMicroHotData(List<Pair<Map<String,Object>, List<Map<String,Object>>>> result) {
		
		if(null == result) return;
		
		if(mIsGetMore){ // 获取更多
			mWbListData.addAll(result); 
		}else{ // 普通刷新
			mWbListData.clear();
			mWbListData.addAll(result);
		}
		
		// 填充list
		if(null == mMicroHotAdapter){
			mMicroHotAdapter = new MicroHotAdapter(mContext, mWbListData);
			mMicroHotListView.setAdapter(mMicroHotAdapter);
		}
		mMicroHotAdapter.notifyDataSetChanged();
	}
	
	@Override
    public void onApplyTheme() {
		
        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
        Context context = getActivity();

        if (getMoreButton() != null) {
            themeSettingsHelper.setViewBackgroud(context, getMoreButton(),
                    R.drawable.netease_big_button);
            themeSettingsHelper.setTextViewColor(context, getMoreButton(), R.color.list_title_color);
        }
        themeSettingsHelper.setViewBackgroud(mContext, v.findViewById(R.id.whole_space_layout), R.drawable.microhot_layout_bg);
    }
	
}
